<template>
  <a-spin :spinning="loading">
    <div class="p-2">
      <!--查询区域-->
      <div class="jeecg-basic-table-form-container">
        <a-form ref="formRef" @keyup.enter="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row :gutter="24">
          </a-row>
        </a-form>
      </div>
      <!--引用表格-->
      <BasicTable @register="registerTable">
        <!--插槽:table标题-->
        <template #tableTitle>
          <super-query :config="superQueryConfig" @search="handleSuperQuery" />
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
      <!-- 表单区域 -->
      <ExamPwdModal ref="registerModal" @success="handleSuccess"></ExamPwdModal>
    </div>

    <!-- 分析图弹框 -->
    <a-modal
      v-model:open="isAnalysisModalVisible"
      title=""
      @ok="handleAnalysisCancel"
      @cancel="handleAnalysisCancel"
      width="70%"
    >
      <!-- 弹框内容 -->
      <div>
        <div style='padding-top: 30px;font-size: 30px;text-align: center;font-weight: bold;'>考生成绩分析报告</div>
        <div style="display: flex;text-align: right;width: 100%;">
          <div style='text-align: center;margin-left: 550px;margin-top: 10px;font-size: 20px;'>口令：{{ currentPasscode }}</div>
          <div style='text-align: center;margin-left: 50px;margin-top: 10px;font-size: 20px;'>总人数：{{ recordsDetail.records.length }}</div>
          <div style="text-align: center;margin-left: 50px;margin-top: 10px;">
            <a-button @click="exportData" type="primary">导出成绩</a-button>
          </div>
        </div>

        <div style="text-align: center;margin: 0 auto;" class="custom-antd-table-wrapper">
          <a-table
            :pagination="false"
            :columns="columnss"
            :data-source="recordsDetail.tu"
            row-key="id"
            bordered
            :scroll="{ x: 'max-content', y: '400px',hideOnSinglePage:true }"
          >
            <template #headerCell="{ title }">
              <div class="custom-header">{{ title }}</div>
            </template>
            <template #headerRow>
              <tr class="custom-header-row">
                <th v-for="col in columnss" :key="col.key" class="custom-header">
                  {{ col.title }}
                </th>
              </tr>
            </template>
          </a-table>
        </div>
        
        <!-- 图表区域 -->
        <div style="display: flex; justify-content: space-between; align-items: center;margin: 20px;margin-left:100px;">
          <div ref="chart" style="width: 80%; height: 600px;"></div>
        </div>
        
        <!-- 动态生成图表 -->
        <div class="chart-grid">
          <div 
            v-for="(chartData, title, index) in dynamicChartData" 
            :key="title"
            class="chart-item"
          >
            <div style="text-align: center; font-size: 20px; margin: 10px;">{{ title }}</div>
            <div 
              :ref="`chart_${index}`" 
              :id="`chart_${index}`" 
              style="width: 100%; height: 600px;">
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </a-spin>
</template>

<script lang="ts" name="examoptions-examPwd" setup>
  import { ref, reactive, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './ExamPwd.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './ExamPwd.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import ExamPwdModal from './components/ExamPwdModal.vue'
  import { useUserStore } from '/@/store/modules/user';
  import * as XLSX from 'xlsx';
  import * as echarts from 'echarts';
  import { message } from 'ant-design-vue';
  import { learnAfter, publicStatistics } from '../tjfx_dt/sc.ts';

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  const router = useRouter();
  
  // 分析图相关数据
  const loading = ref(false);
  const isAnalysisModalVisible = ref(false);
  const currentPasscode = ref('');
  const chart = ref(null);
  
  // 动态图表数据
  const dynamicChartData = reactive({});
  
  // 分析结果数据
  const recordsDetail = reactive({
    records: [],
    tu: []
  });
  
  // 分析表格列配置
  const columnss = reactive([
    {
      title: '题目名称',
      dataIndex: 'title',
      key: 'title',
      width: '300px'
    },
    {
      title: '正确人数',
      dataIndex: 'rightNum',
      key: 'rightNum',
    },
    {
      title: '错误人数',
      dataIndex: 'errorNum',
      key: 'errorNum',
    },
    {
      title: '正确率',
      dataIndex: 'right',
      key: 'right',
    },
    {
      title: '错误率',
      dataIndex: 'error',
      key: 'error',
    },
  ]);
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: 'exam_pwd',
      api: list,
      columns,
      canResize:false,
      useSearchForm: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        console.log(params,"params")
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "exam_pwd",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
   
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '分析图',
        onClick: () => {
          const pass = (record as any)?.passcode || '';
          currentPasscode.value = pass;
          showAnalysisModal(pass);
        },
      },
    ];
  }
   
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return []
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  // 监听 modal 的打开状态
  watch(isAnalysisModalVisible, async (newVal) => {
    if (newVal) {
      // 等待 DOM 渲染完成
      await nextTick();
      await initChart();
      await generateChartData();
      await initCharts();
    }
  });

  // 显示生成分析图的弹框
  const showAnalysisModal = async (passcode: string) => {
    if (!passcode) {
      message.warning('请先选择口令');
      return;
    }
    loading.value = true;
    await learnAfter1({ passcode });
  };

  // 获取分析数据
  const learnAfter1 = async (obj: any) => {
    let par = '';
    if (obj.passcode) {
      par = `?pageNo=1&pageSize=20000&passcode=${obj.passcode}`;
    } else {
      par = `?pageNo=1&pageSize=20000&unitName=${obj.unitName}`;
    }
    const res = await learnAfter(par);
    recordsDetail.records = res.page.records;
    const result = Object.entries(res.tu).map(([title, values]) => ({
      title,
      ...values
    }));
    recordsDetail.tu = result;
    isAnalysisModalVisible.value = true;
    loading.value = false;
  };

  // 根据数据动态生成图表配置
  const generateChartData = async () => {
    const param = { pass: currentPasscode.value };
    const res1 = await publicStatistics(param);
    const questionData = res1;
    const allCharts = { ...questionData["基础信息题"], ...questionData["调查问卷"] };
    Object.entries(allCharts).forEach(([title, answers]) => {
      const categories = answers.map(answer => Object.keys(answer)[0]);
      const data = answers.map(answer => {
        const option = Object.keys(answer)[0];
        const value = Object.values(answer)[0];
        const [key, name] = option.split(":");
        return { value, name: `${name}-${value}` };
      });
      dynamicChartData[title] = {
        title: title,
        categories,
        data
      };
    });
  };

  // 初始化图表
  const initCharts = () => {
    Object.keys(dynamicChartData).forEach((title, index) => {
      const chartDom = document.getElementById(`chart_${index}`);
      if (chartDom) {
        const chart = echarts.init(chartDom);
        const chartData = dynamicChartData[title];
        const option = {
          title: {
            text: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [{
            data: chartData.data,
            type: 'pie',
            radius: '50%',
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }],
        };
        chart.setOption(option);
      }
    });
  };

  // 初始化主图表
  const initChart = () => {
    if (chart.value) {
      const arr1 = [];
      const arr2 = [];
      const arr3 = [];
      recordsDetail.records.forEach(item => {
        arr1.push(item.name);
        arr2.push(item.oneScore);
        arr3.push(item.twoScore);
      });
      const myChart = echarts.init(chart.value);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['第一次考试', '第二次考试']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          show: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: arr1
        },
        series: [
          {
            name: '第一次考试',
            type: 'bar',
            data: arr2,
            label: {
              show: true,
              position: 'insideRight'
            }
          },
          {
            name: '第二次考试',
            type: 'bar',
            data: arr3,
            label: {
              show: true,
              position: 'insideRight'
            }
          }
        ]
      };
      myChart.setOption(option);
    }
  };

  // 关闭分析图弹框
  const handleAnalysisCancel = () => {
    isAnalysisModalVisible.value = false;
  };

  // 导出数据
  const exportData = () => {
    const formattedData = recordsDetail.records.map(item => ({
      '题目名称': item.bankName,
      '姓名': item.name,
      '单位名称': item.unitName,
      '第一次成绩': item.oneScore,
      '第二次成绩': item.twoScore,
      '第一次创建时间': item.oneCreateTime,
      '第二次创建时间': item.twoCreateTime,
      '第一次答题总数': item.onetotalNum,
      '第二次答题总数': item.twototalNum,
      '第一次正确数': item.oneRightNum,
      '第一次错误数': item.oneWrongNum,
      '第二次正确数': item.twoRightNum,
      '第二次错误数': item.twoWrongNum,
    }));

    const ws = XLSX.utils.json_to_sheet(formattedData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '成绩数据');
    XLSX.writeFile(wb, '考试成绩分析报告.xlsx');
  };
  



</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }

  .chart-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
  }

  .chart-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .custom-antd-table-wrapper {
    height: 100%;
    ::v-deep(.ant-table-wrapper) {
      height: 100%;
      .ant-spin-nested-loading {
        height: 100%;
      }
      .ant-spin-container {
        height: 100%;
        display: flex;
        flex-direction: column;
        .ant-table {
          flex: 1;
          height: 0;
        }
        .ant-pagination {
          flex-shrink: 0;
        }
      }
      .ant-table-container {
        height: 100%;
        display: flex;
        flex-direction: column;
        > .ant-table-header {
          flex-shrink: 0;
        }
        > .ant-table-body {
          flex: 1;
          height: 0;
        }
      }
    }
  }

  .custom-header-row {
    background-color: #efc004;
  }

  .custom-header {
    padding: 8px;
    text-align: center;
    font-weight: bold;
  }
</style>
